package com.heima.behavior.advice;

import com.heima.behavior.dto.BehaviorDto;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class BehaviorAdvice {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Around("execution(* com.heima.behavior.service.impl.*.*(..))")
    public Object recordToRedis(ProceedingJoinPoint point)throws Throwable{
        MethodSignature signature = (MethodSignature) point.getSignature();
        Object[] args = point.getArgs();
        String name = signature.getMethod().getName();
        if(name.startsWith("save")){
            BehaviorDto dto = (BehaviorDto) args[0];
            if(dto.getOperation() == 0){
                //redis中的key包含了“行为+用户id+设备id+文章id
                redisTemplate.boundValueOps(name+"_"+dto.getUserId()+"_"+dto.getEquipmentId()+"_"+dto.getArticleId()).set("");
            }else {
                redisTemplate.delete(name+"_"+dto.getUserId()+"_"+dto.getEquipmentId()+"_"+dto.getArticleId());
            }
        }
        return point.proceed(args);
    }
}
